package utils

import (
	"errors"
	"flag"
	"os/exec"
)

/**
  @author: light
  @since: 2023/9/4
  @desc: 命令行工具
*/

type Command struct {
	Order string
	Dir   string
	Flags []Flag
}

type Flag struct {
	Name         string
	DefaultValue string
	Usage        string
}

func (c *Command) Exec() (string, error) {
	if 0 == len(c.Dir) {
		return "", errors.New("必须指定工作目录")
	}
	cmd := exec.Command("sh", "-c", c.Order)
	cmd.Dir = c.Dir
	output, err := cmd.CombinedOutput()
	return string(output), err
}

func (c *Command) ParseString() (map[string]string, error) {
	resultMap := make(map[string]string)
	if 0 == len(c.Flags) {
		return resultMap, errors.New("未识别到命令输入")
	}
	cmdResult := make([]*string, 0)
	for _, f := range c.Flags {
		cmdResult = append(cmdResult, flag.String(f.Name, f.DefaultValue, f.Usage))
	}
	flag.Parse()
	for index, f := range c.Flags {
		resultMap[f.Name] = *cmdResult[index]
	}
	return resultMap, nil
}
